package org.kingtop.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import org.apache.shiro.codec.Base64;

/**
 * 部分无法通过json序列化的类需要通过这个进行序列化
 * <p>
 * User: Zhang Kaitao
 * <p>
 * Date: 14-2-8
 * <p>
 * Version: 1.0
 */
public class SerializableUtils {

	/**
	 * 序列化
	 * 
	 * @param session
	 * @return
	 */
	public static String serialize(Object session) {
		if (!(session instanceof Serializable)) {
			throw new IllegalArgumentException(
					SerializableUtils.class.getSimpleName() + " requires a Serializable payload "
							+ "but received an object of type [" + session.getClass().getName() + "]");
		}
		try {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(bos);
			oos.writeObject(session);
			return Base64.encodeToString(bos.toByteArray());
		} catch (Exception e) {
			throw new RuntimeException("serialize session error", e);
		}
	}

	/**
	 * 反序列化
	 * 
	 * @author 陈金波
	 * @Description 反序列化
	 * @param sessionStr
	 * @return Object
	 */
	public static Object deserialize(String sessionStr) {
		try {
			ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decode(sessionStr));
			ObjectInputStream ois = new ObjectInputStream(bis);
			return ois.readObject();
		} catch (Exception e) {
			throw new RuntimeException("deserialize session error", e);
		}
	}
}
